package com.singleton.demo03;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class ConfigManager {
    /**
     * 属性配置文件全路径名
     */
    private static final String FILEPATH = System.getProperty("user.dir") +  "/Singleton.properties";

    /**
     * 配置文件对应的 File 实例
     */
    private File file = null;

    /**
     * File的最后修改时间
     */
    private long lastModifiedTime = 0;

    /**
     * File映射成的属性对象
     */
    private Properties pro = null;

    /**
     * 该类的唯一实例(饿汉式)
     */
    private static ConfigManager instance = new ConfigManager();

    private ConfigManager() {
        file = new File(FILEPATH);
        lastModifiedTime = file.lastModified();

        if(lastModifiedTime == 0){
            System.err.println(FILEPATH + " file does not exist!");
        }

        pro = new Properties();
        try{
            pro.load(new FileInputStream(FILEPATH));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 返回单例实例
     */
     public static synchronized ConfigManager getInstance() {
        return instance;
    }

    /**
     * @param name: 属性文件中key名
     * @param defaultVal: 属性的默认值.获取不到该name对应的属性值,就返回 defaulVal.
     *
     * @return 根据给定的name,从属性文件中获取该name对应的属性值
     *
     */
     public final Object getConfigItem(String name, Object defaultVal) {
        long newTime = file.lastModified();

        /**
         * 检查属性文件是否被修改(多数情况下是程序员手动修改了)
         * 如果是,重新读取此文件.
         */
        if(newTime == 0){
            // The props file was deleted or does not exist (!!)
            if(lastModifiedTime == 0) {// 属性文件不存在(Singleton.properties)
                System.err.println(FILEPATH + " file does not exist!");
            } else {// 属性文件被删除
                System.err.println(FILEPATH + " file was deleted!!");
            }
            return defaultVal;
        } else if(newTime > lastModifiedTime) {// 属性文件被修改
            pro.clear();
            try{
                pro.load(new FileInputStream(FILEPATH));
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        lastModifiedTime = newTime;

        Object val = pro.getProperty(name);
        if( val == null ) {
            return defaultVal;
        } else {
            return val;
        }
    }

}
